<template>
  <div class="params">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 警告 -->
      <el-alert title="注意：只能为第三级分类设置相关参数" type="warning" :closable="false" show-icon></el-alert>
      <!-- 级联选择器 ------------------------------------>
      <el-row class="cat_otp">
        <el-col>
          <span>选择商品分类：</span>
          <!-- options 父级数据源 v-model 选中暂存 props 设置显示属性 -->
          <el-cascader
            v-model="selectedCate"
            :options="cateList"
            :props="{ expandTrigger: 'hover',label:'cat_name',value:'cat_id',children:'children'}"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- Tabs活动页 ------------------------------------>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态数据 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 按钮 -->
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addProps">添加参数</el-button>
          <!-- 动态属性表格 -->
          <el-table :data="manyTableData" border stripe style="width:100%">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <!-- tag标签 -->
                <el-tag
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="tagClosed(scope.row,index)"
                >{{item}}</el-tag>
                <!-- 添加tag -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 序号 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作" width="300px">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editPropsBtn(scope.row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteProps(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态数据 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 按钮 -->
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addProps">添加参数</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe style="width:100%">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <!-- tag标签 -->
                <el-tag
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="tagClosed(scope.row,index)"
                >{{item}}</el-tag>
                <!-- 添加tag -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 序号 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作" width="300px">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editPropsBtn(scope.row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteProps(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <el-row class="cat_otp">
        <el-col></el-col>
      </el-row>
    </el-card>
    <!-- Dialog -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addPropsDialogVisible"
      width="50%"
      @close="addPropsDialogClosed"
    >
      <!-- 表单 -->
      <el-form
        :model="addPropsFormData"
        :rules="addPropsRules"
        ref="addPropsRef"
        label-width="100px"
      >
        <!-- 输入框 -->
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addPropsFormData.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addPropsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="postProps">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑按钮Dialog -->
    <el-dialog title="编辑" :visible.sync="editDialogVisible" width="50%">
      <el-form
        :model="editPropsFrom"
        :rules="editPropsRules"
        ref="editPropsFormRef"
        label-width="100px"
      >
        <el-form-item label="编辑属性:" prop="attr_name">
          <el-input v-model="editPropsFrom.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDialogSub">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 请求获取的全部分类
      cateList: [],
      // 展现指定分类
      showCateList: [],
      // 已选分类数据暂存区
      selectedCate: [],
      // 设置哪个被页签激活
      activeName: 'many',
      // 暂存区数据
      manyTableData: [],
      onlyTableData: [],

      // dialog显示
      editDialogVisible: false,
      addPropsDialogVisible: false,

      // 规则
      addPropsRules: [],
      editPropsRules: [],

      // 输入框的数据
      addPropsFormData: {
        attr_name: ''
      },
      editPropsFrom: {
        attr_name: '',
        attr_id: ''
      },

      // 添加表单的验证规则对象
      addPropsRules: {
        attr_name: { required: true, message: '请输入属性', trigger: 'blur' }
      },
      editPropsRules: {
        attr_name: { required: true, message: '请输入属性', trigger: 'blur' }
      }
    }
  },
  computed: {
    // 按钮是否可用
    isBtnDisabled() {
      if (this.selectedCate.length !== 3) {
        return true
      }
      return false
    },
    // 选中三级分类的id
    cateId() {
      if (this.selectedCate.length == 3) {
        return this.selectedCate[2]
      }
      return null
    },
    // Dialog动态标题文本
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态参数'
      }
    }
  },
  methods: {
    // 删除tag
    async tagClosed(row, index) {
      console.log('tagClosed', index, row)
      // 删除操作splice,修改数组不需要赋值
      row.attr_vals.splice(index, 1)
      this.saveTagsProps(row)
    },
    // 显示输入框
    showInput(row) {
      row.inputVisible = true
      // 等input渲染后,执行$nextTick
      // $nextTick 当页面dom重新渲染后执行
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 输入框确认后
    async handleInputConfirm(row) {
      // trim去除两端空格
      if (row.inputValue.trim().length === 0) {
        ;(row.inputValue = ''), (row.inputVisible = false)
        return
      }
      // 增加tag数组
      row.attr_vals.push(row.inputValue.trim())
      // 重置文本框,隐藏文本框
      row.inputValue = ''
      row.inputVisible = false
      this.saveTagsProps(row)
    },
    // put请求:保存tags属性
    async saveTagsProps(row) {
      console.log('put当前tags属性', row)
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      console.log('put返回数据', res)
      if (res.meta.status !== 200) {
        return this.$message.error(`${res.meta.msg}`)
      }
      this.$message.success(`${res.meta.msg}`)
      // 这里不用更新属性,tags已有动画呈现删除显示
    },
    // 编辑提交
    editDialogSub() {
      this.$refs.editPropsFormRef.validate(async valid => {
        // 没校验成功
        if (!valid) return
        // 校验成功
        const {
          data: res
        } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editPropsFrom.attr_id}`,
          { attr_name: this.editPropsFrom.attr_name, attr_sel: this.activeName }
        )
        console.log('编辑请求返回数据', res)
        // 编辑失败
        if (res.meta.status !== 200) {
          return this.$message.error(`${res.meta.msg}`)
        }
        // 编辑成功
        this.$message.success(`${res.meta.msg}`)
        this.getParamsData()
        // 关闭对话框
        this.editDialogVisible = false
      })
    },
    // 点击编辑按钮事件
    async editPropsBtn(data) {
      console.log('当前编辑', data)
      this.editPropsFrom.attr_name = data.attr_name
      this.editPropsFrom.attr_id = data.attr_id
      this.editDialogVisible = true
    },
    // 点击删除按钮
    async deleteProps(data) {
      console.log('当前删除数据', data)
      const confirmResult = await this.$confirm(
        '此操作将永久删除该属性, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${data.attr_id}`
      )
      console.log('删除请求返回数据', res)
      if (res.meta.status !== 200) {
        return this.$message.error(`${res.meta.msg}`)
      }
      this.$message.success(`${res.meta.msg}`)
      this.getParamsData()
    },
    // 提交请求: 添加属性
    postProps() {
      console.log(this.activeName)
      this.$refs.addPropsRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addPropsFormData.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error(`${res.meta.msg}`)
        }
        this.$message.success(`${res.meta.msg}`)
        this.addPropsDialogVisible = false
        this.getParamsData()
      })
    },
    // 重置表单
    editPropsDialogClosed() {
      this.$refs.editPropsFormRef.resetFields()
    },
    addPropsDialogClosed() {
      this.$refs.addPropsRef.resetFields()
    },
    addProps() {
      this.addPropsDialogVisible = true
    },
    // 切换tabs标签时
    handleTabClick() {
      console.log('当前点击标签页名字', this.activeName)
      this.getParamsData()
    },
    // 级联选择器 选择改变时 事件
    handleChange() {
      this.getParamsData()
    },
    // 获取商品分类列表--选择器使用
    async getCateList() {
      const { data: res } = await this.$http.get(`categories`)
      if (res.meta.status !== 200) {
        return this.$message.error(`${res.meta.msg}`)
      }
      this.$message.success(`${res.meta.msg}`)
      // 导入数据
      this.cateList = res.data
      console.log('获取全部分类:', this.cateList)
    },
    // 获取指定参数(get)--更新动态静态数据
    async getParamsData() {
      // 如果没有选择
      if (this.selectedCate.length !== 3) {
        this.$message.error('请选择三级分类')
        this.selectedCate = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // 如果选择了,发请求==========================
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(`${res.meta.msg}`)
      }
      console.log('选中三级分类的属性', res.data)
      // 字符串切割后变成数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 添加tag添加框的显示隐藏,值
        ;(item.inputVisible = false), (item.inputValue = '')
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
        console.log('动态参数:', this.manyTableData)
      } else {
        this.onlyTableData = res.data
        console.log('静态参数:', this.onlyTableData)
      }
      this.$message.success(`${res.meta.msg}`)
    }
  },
  created() {
    this.getCateList()
  }
}
</script>

<style scoped>
.cat_otp {
  margin-top: 15px;
}
.el-tag {
  margin-left: 10px;
  margin-top: 15px;
}
/* 新建tag按钮 */
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
/* tag输入框 */
.input-new-tag {
  margin-left: 10px;
  width: 90px;
  vertical-align: bottom;
}
</style>